*** Settings ***
Library    RequestsLibrary
Library    Collections
Library    String

Suite Setup    Create Session    api    http://127.0.0.1:5000
Suite Teardown    Delete All Sessions

*** Variables ***
${BASE_URL}    http://127.0.0.1:5000

*** Test Cases ***
添加人员信息
    ${random_name}=    Generate Random String    8    [LETTERS]
    Set Suite Variable    ${random_name}    ${random_name}
    ${headers}=    Create Dictionary    Content-Type=application/json
    ${data}=    Create Dictionary
    ...    name=${random_name}
    ...    age=25
    ...    gender=男
    ...    phone=13800138000

    ${response}=    POST On Session    api    /api/persons
    ...    json=${data}
    ...    headers=${headers}

    Should Be Equal As Numbers    ${response.status_code}    201
    Dictionary Should Contain Key    ${response.json()}    id
    Should Be Equal As Strings    ${response.json()}[name]    ${random_name}
    Set Suite Variable    ${person_id}    ${response.json()}[id]

获取所有人员信息
    ${response}=    GET On Session    api    /api/persons

    Should Be Equal As Numbers    ${response.status_code}    200
    ${list_length}=    Get Length    ${response.json()}
    Should Be True    ${list_length} > 0

搜索人员信息
    ${response}=    GET On Session    api    /api/persons
    ...    params=search=${random_name}

    Should Be Equal As Numbers    ${response.status_code}    200
    ${found}=    Set Variable    False
    FOR    ${person}    IN    @{response.json()}
        ${found}=    Set Variable If    '${person}[name]' == '${random_name}'    True    ${found}
    END
    Should Be True    ${found}    msg=未找到名为${random_name}的人员

获取单个人员信息
    ${response}=    GET On Session    api    /api/persons/${person_id}

    Should Be Equal As Numbers    ${response.status_code}    200
    Should Be Equal As Strings    ${response.json()}[name]    ${random_name}
    Should Be Equal As Numbers    ${response.json()}[age]    25

更新人员信息
    ${headers}=    Create Dictionary    Content-Type=application/json
    ${update_data}=    Create Dictionary
    ...    name=更新后的名字
    ...    age=30
    ...    gender=女
    ...    phone=13900139123

    ${response}=    PUT On Session    api    /api/persons/${person_id}
    ...    json=${update_data}
    ...    headers=${headers}

    Should Be Equal As Numbers    ${response.status_code}    200
    Should Be Equal As Strings    ${response.json()}[name]    更新后的名字
    Should Be Equal As Numbers    ${response.json()}[age]    30

删除人员信息
    # 首先获取人员确保存在
    ${response}=    GET On Session    api    /api/persons/${person_id}
    Should Be Equal As Numbers    ${response.status_code}    200

    # 然后删除
    ${response}=    DELETE On Session    api    /api/persons/${person_id}
    Should Be Equal As Numbers    ${response.status_code}    200

    # 最后验证已删除
    ${response}=    GET On Session    api    /api/persons/${person_id}    expected_status=404
    Should Be Equal As Numbers    ${response.status_code}    404